/**
 * 
 */
package org.gbif.crawler.console.servlet.tail;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * This is a simple servlet that will allow users to tail a file through the browser
 * For security, the prefix of the requested file is checked
 * @author tim
 */
public class LogTailServlet extends HttpServlet {
  private static final String LINE_BREAK = "<BR/>";
  public static final String PARAM_PATH = "path";
  public static final String PARAM_FROM = "from"; 
  private static String pathRoot = "/tmp/harvest/";
  
  private List<Decorator> decorators = new LinkedList<Decorator>();
  
  
  
  @Override
  public void init() throws ServletException {
    decorators.add(new LinkDecorator());
    decorators.add(new ExceptionDecorator());
    decorators.add(new IndentedLineDecorator());
    decorators.add(new WhitespaceDecorator());
  }

  @Override
  protected void doGet(HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    // extract the config
    String path  = req.getParameter(PARAM_PATH);
    int fromLine =0;
    if (req.getParameter(PARAM_FROM)!=null) {
      try {
        fromLine = Integer.parseInt(req.getParameter(PARAM_FROM));
      } catch (NumberFormatException e) {}
    }
    
    resp.setContentType("text/html");
    OutputStream out = resp.getOutputStream();
    
    // only tail files with a recognised path for security reasons (e.g. don't open all machine access)
    if (path != null && path.startsWith(pathRoot)) {
      BufferedReader reader = null;
      try {
        reader = new BufferedReader(new FileReader(path));
        
        String line = reader.readLine();
        int linesRead = 0;
        while (line != null) {
          linesRead++;
          
          if (linesRead > fromLine) {
            
            for (Decorator d : decorators) {
              line = d.decorate(line);
            }
            
            IOUtils.write(line, out);
            IOUtils.write(LogTailServlet.LINE_BREAK, out);
          }
          
          line = reader.readLine();
        }
        
        // set a custom header so the client knows the next request to tail
        resp.setHeader("from", "" + linesRead);
        
        
      } finally {
        IOUtils.closeQuietly(reader);
      }
    }
    
    out.flush();
    out.close();
  }
  
  public static void main(String[] args) {
    try {
      throw new Exception("test");
    } catch (Exception e){
      e.printStackTrace();
    }
  }
}